package com.keyboardr.gamerater;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class Group implements JSONable, Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 3430092895639964731L;
	private String name;
	private boolean fide;
	private ArrayList<Player> players;
	private ArrayList<Game> games;
	
	public Group(CharSequence name, boolean fide){
		this.name = name.toString();
		this.fide = fide;
		players = new ArrayList<Player>();
		games = new ArrayList<Game>();
	}
	
	public Group(JSONObject jObject){
		try {
			name = jObject.getString("name");
			fide = jObject.getBoolean("fide");
			JSONArray playerArray = jObject.getJSONArray("players");
			JSONArray gamesArray = jObject.getJSONArray("games");
			players = new ArrayList<Player>(playerArray.length());
			games = new ArrayList<Game>(gamesArray.length());
			for(int i = 0; i < playerArray.length(); i++){
				players.add(new Player(playerArray.getJSONObject(i)));
			}
			for(int i = 0; i < gamesArray.length(); i++){
				games.add(new Game(gamesArray.getJSONObject(i), players));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * @return the players
	 */
	public ArrayList<Player> getPlayers() {
		return new ArrayList<Player>(players);
	}
	
	public void addPlayer(Player player){
		players.add(player);
	}
	
	public void removePlayer(Player player){
		players.remove(player);
	}
	
	public boolean isFide(){
		return fide;
	}
	
	public ArrayList<Game> getGames() {
		return new ArrayList<Game>(games);
	}
	public void playAGame(boolean draw, Player winner, Player loser){
		Game game = new Game(draw, winner, loser, new Date(), fide, players);
		games.add(game);
		game.applyGame();
	}
	
	@Override
	public String toString(){
		return new String(name);
	}


	@Override
	public JSONObject toJSON() {
		JSONObject jObject = new JSONObject();
		try {
			jObject.put("name", name);
			jObject.put("fide", fide);
			JSONArray playerArray = new JSONArray();
			for(Player player : players){
				playerArray.put(player.toJSON());
			}
			JSONArray gamesArray = new JSONArray();
			for(Game game : games){
				gamesArray.put(game.toJSON());
			}
			jObject.put("players",playerArray);
			jObject.put("games", gamesArray);
			Log.d("Group", jObject.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jObject;
	}
}
